<?php
include_once(constant('PATH_INCLUDE').'/class.validatecode.php');
$GLOBALS['needValidCode'];
$GLOBALS['needValidCode'] = isset($_REQUEST['showvalidcode'])?true:false;

if ( isset($_POST['username']) AND isset($_POST['password'])) {
	$userDT = new DataTable(constant('DB_TABLE_USER'));
	$condition = sprintf("`login_user`='%s' AND `is_active`='Y'",Util::sql_safe($_REQUEST['username']));
	$userData = $userDT->get_row($condition);
	if(empty($userData))
	{
		throw new Exception('帳號不存在.');
	}
	$max_try_times = intval(Util::getGlobalValue('MAX_USER_TRY_SIGNIN_TIMES_'.$userData['id']));
	if($max_try_times >constant('MAX_USER_TRY_SIGNIN_TIMES'))
	{
		$GLOBALS['needValidCode'] = TRUE;
		if(empty($_REQUEST['validatecode']))
		{
			
			throw new Exception('請錄入驗證碼.');
		}
		if($GLOBALS['needValidCode'])
		{
			if( empty($_REQUEST['validatecode']))
				throw new Exception('請錄入驗證碼.');
			if(!ValidateCode::isUserSigninCodeCorrect($_REQUEST['validatecode']))
				throw new Exception('驗證碼不正確.');
		}
	}
	if($userData['login_password'] != md5($_REQUEST['password']))
	{
		$max_try_times++;
		Util::setGlobalValue('MAX_USER_TRY_SIGNIN_TIMES_'.$userData['id'],$max_try_times);
		throw new Exception('帳戶或者密碼不正確.');
	
	}
	SessionUtil::setVar(constant('SESSION_KEY_HAS_LOGIN'),'1');
	Util::deleteGlobalValue('MAX_USER_TRY_SIGNIN_TIMES_'.$userData['id']);
	SessionUtil::removeVar(constant('SESSION_KEY_USER_SIGN_VALIDATE_CODE'));
	
	SessionUtil::setVar(constant('SESSION_KEY_USER_ID'),$userData['id']);
	SessionUtil::setVar(constant('SESSION_KEY_USER_NAME'),$userData['login_user']);
	
	//update admin last login information
	$last_login_info = array();
	$last_login_info['id'] = $userData['id'];
	$last_login_info['ll_time'] = date('Y-m-d H:i:s');
	$last_login_info['ll_ip'] = Util::getRemoteIP();
	$userDT->save($last_login_info);
	ob_clean();
	header('Location:main.php');
}
?>